#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
@author: yinzhuoqun
@site: http://xieboke.net/
@email: yin@zhuoqun.info
@time: 2020/9/29 11:33
"""
from django.db import IntegrityError
from django.contrib import messages


class ProtectedError(IntegrityError):
    def __init__(self, request, msg, protected_objects):
        self.protected_objects = protected_objects
        super().__init__(msg, protected_objects)
        messages.error(request, msg)


def PROTECT(collector, field, sub_objs, using):
    print("************* protect")
    raise ProtectedError(
        "Cannot delete some instances of model '%s' because they are "
        "referenced through a protected foreign key: '%s.%s'" % (
            field.remote_field.model.__name__, sub_objs[0].__class__.__name__, field.name
        ),
        sub_objs
    )
